﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using Newtonsoft.Json.Linq;
using System.Data;
using System.Text.RegularExpressions;
using System.Net;
using System.Text;
using System.IO;
using SZHL.Data;
using System.Security.Cryptography;

namespace SZHL.UI.AppCode
{
    public class CommonHelp
    {
        /// <summary>
        /// 绑定类
        /// </summary>
        public class BindData
        {
            /// <summary>
            /// 绑定部门
            /// </summary>
            /// <param name="ddl"></param>
            public void BindBranch(DropDownList ddl, string strISALL = "N")
            {
                if (strISALL == "N")
                {
                    ddl.DataSource = new JH_Auth_BranchB().GetEntities(d => d.DeptCode != 0 && d.DeptCode != 1);

                }
                else
                {
                    ddl.DataSource = new JH_Auth_BranchB().GetEntities(d => d.DeptCode != 0);
                }
                ddl.DataTextField = "DeptName";
                ddl.DataValueField = "DeptCode";
                ddl.DataBind();
            }


            /// <summary>
            /// 绑定页码
            /// </summary>
            /// <param name="ddl"></param>
            /// <param name="Page"></param>
            public void BindPage(DropDownList ddl, int Page)
            {
                ddl.Items.Clear();
                if (Page == 0)
                {
                    ddl.Items.Add(new ListItem() { Text = "1", Value = "1" });
                }
                else
                {
                    for (int i = 1; i <= Page; i++)
                    {
                        ddl.Items.Add(new ListItem() { Text = i.ToString(), Value = i.ToString() });
                    }
                }

            }

            public void BindAllPeopleSmart(DropDownList ddl)
            {
                ListItem liFirst = new ListItem("请选择", "");
                ddl.Items.Add(liFirst);
                List<JH_Auth_Branch> ListBranch = new JH_Auth_BranchB().GetEntities(d => d.DeptName != "组织机构").ToList();
                foreach (var item in ListBranch)
                {
                    ListItem liBranch = new ListItem(item.DeptName, "optgroup");
                    ddl.Items.Add(liBranch);
                    string strListUsers = new JH_Auth_UserB().GetAllUserListByBranch(item.DeptCode).Trim();
                    if (strListUsers.Length > 0)
                    {
                        foreach (var itemuser in strListUsers.Split(','))
                        {
                            if (itemuser != "admin")
                            {
                                ListItem liUser = new ListItem(new JH_Auth_UserB().GetUserRealName(itemuser), itemuser);
                                ddl.Items.Add(liUser);
                            }

                        }
                    }
                }
            }




            #region 业务绑定

            /// <summary>
            /// 绑定字典数据
            /// </summary>
            /// <param name="ddl"></param>
            /// <param name="strClass"></param>
            public void BindZiDian(DropDownList ddl, string strClass)
            {

                ddl.DataSource = new JH_Auth_ZiDianB().GetEntities(d => d.Class.ToString() == strClass);
                ddl.DataTextField = "TypeName";
                ddl.DataValueField = "TypeName";
                ddl.DataBind();
            }


            /// <summary>
            /// 绑定审核人（出差请假，经费报销）
            /// </summary>
            /// <param name="ddl"></param>
            /// <param name="strClass"></param>
            public void BindSHR(DropDownList ddl, int strRoleCode = 4)
            {

                ddl.DataSource = new JH_Auth_UserRoleB().GetUserDTByRoleCode(strRoleCode);
                ddl.DataTextField = "userrealname";
                ddl.DataValueField = "username";
                ddl.DataBind();
            }


            #endregion
        }


        public class SessionHelper
        {
            /// <summary>
            /// 根据session名获取session对象
            /// </summary>
            /// <param name="name"></param>
            /// <returns></returns>
            public static object GetSession(string name)
            {
                return HttpContext.Current.Session[name];
            }
            /// <summary>
            /// 设置session,sharejs.com
            /// </summary>
            /// <param name="name">session 名</param>
            /// <param name="val">session 值</param>
            public static void SetSession(string name, object val)
            {
                HttpContext.Current.Session.Remove(name);
                HttpContext.Current.Session.Add(name, val);
            }
        }


        /// <summary>
        /// 从html中提取纯文本
        /// </summary>
        /// <param name="strHtml"></param>
        /// <returns></returns>
        public string StripHT(string strHtml)  //从html中提取纯文本
        {
            Regex regex = new Regex("<.+?>", RegexOptions.IgnoreCase);
            string strOutput = regex.Replace(strHtml, "");//替换掉"<"和">"之间的内容
            strOutput = strOutput.Replace("<", "");
            strOutput = strOutput.Replace(">", "");
            strOutput = strOutput.Replace("&nbsp;", "");
            return strOutput;
        }

        /// <summary>  
        /// 创建POST方式的HTTP请求  
        /// </summary>  
        public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, int timeout, string userAgent, CookieCollection cookies)
        {
            HttpWebRequest request = null;
            //如果是发送HTTPS请求  
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(url) as HttpWebRequest;
                //request.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            //设置代理UserAgent和超时
            //request.UserAgent = userAgent;
            //request.Timeout = timeout; 

            if (cookies != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookies);
            }
            //发送POST数据  
            if (!(parameters == null || parameters.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, parameters[key]);
                        i++;
                    }
                }
                byte[] data = Encoding.UTF8.GetBytes(buffer.ToString());
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            string[] values = request.Headers.GetValues("Content-Type");
            return request.GetResponse() as HttpWebResponse;
        }

        /// <summary>
        /// 获取请求的数据
        /// </summary>
        public static string GetResponseString(HttpWebResponse webresponse)
        {
            using (Stream s = webresponse.GetResponseStream())
            {
                StreamReader reader = new StreamReader(s, Encoding.UTF8);
                return reader.ReadToEnd();

            }
        }

        public static string PostFile(string uploadUrl, string fileToUpload, string poststr = "")
        {
            string result = "";

            try
            {
                string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
                HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uploadUrl);
                webrequest.ContentType = "multipart/form-data; boundary=" + boundary;
                webrequest.Method = "POST";
                StringBuilder sb = new StringBuilder();
                if (poststr != "")
                {
                    foreach (string c in poststr.Split('&'))
                    {
                        string[] item = c.Split('=');
                        if (item.Length != 2)
                        {
                            break;
                        }
                        string name = item[0];
                        string value = item[1];
                        sb.Append("–" + boundary);
                        sb.Append("\r\n");
                        sb.Append("Content-Disposition: form-data; name=\"" + name + "\"");
                        sb.Append("\r\n\r\n");
                        sb.Append(value);
                        sb.Append("\r\n");
                    }
                }
                sb.Append("--");
                sb.Append(boundary);
                sb.Append("\r\n");
                sb.Append("Content-Disposition: form-data; name=\"file");
                //sb.Append(fileFormName);
                sb.Append("\"; filename=\"");
                sb.Append(Path.GetFileName(fileToUpload));
                sb.Append("\"");
                sb.Append("\r\n");
                sb.Append("Content-Type: application/octet-stream");
                //sb.Append(contenttype);
                sb.Append("\r\n");
                sb.Append("\r\n");
                string postHeader = sb.ToString();
                byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);
                byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
                FileStream fileStream = new FileStream(fileToUpload, FileMode.Open, FileAccess.Read);
                long length = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length;
                webrequest.ContentLength = length;
                Stream requestStream = webrequest.GetRequestStream();
                requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
                byte[] buffer = new Byte[(int)fileStream.Length];
                int bytesRead = 0;
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    requestStream.Write(buffer, 0, bytesRead);
                }
                requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                fileStream.Close();
                WebResponse responce = webrequest.GetResponse();
                requestStream.Close();
                using (Stream s = responce.GetResponseStream())
                {
                    using (StreamReader sr = new StreamReader(s))
                    {
                        result = sr.ReadToEnd();
                    }
                }

                //if (File.Exists(fileToUpload))
                //{
                //    File.Delete(fileToUpload);
                //}

               
            }
            catch (Exception ex)
            {
                //CommonHelp.WriteLog(ex.Message);
            }
            return result;
        }

        public static string ProcessWxIMG(string mediaIds,string username)
        {
            string ids = "";
            foreach (var mediaId in mediaIds.Split(','))
            {
                string fileToUpload = WXHelp.GetMediaFile(mediaId);
                string md5 = PostFile(WXHelp.FileServerUrlUpload, fileToUpload);

                System.IO.FileInfo f = new FileInfo(fileToUpload);

                FT_File newfile = new FT_File();
                newfile.Name = f.Name;
                newfile.FileMD5 = md5.Replace("\"", "");
                newfile.FileSize = f.Length.ToString();
                newfile.FileVersin = 0;
                newfile.CRDate = DateTime.Now;
                newfile.CRUser = username;
                newfile.UPDDate = DateTime.Now;
                newfile.UPUser = username;
                //newfile.FolderID = int.Parse(P2);
                newfile.FileExtendName = f.Extension.Substring(1);
                if (new List<string>() { "pdf", "txt", "html", "doc", "docx", "ppt", "pptx", "mp4", "flv", "ogg" }.Contains(newfile.FileExtendName))
                {
                    newfile.ISYL = "Y";
                }

                new FT_FileB().Insert(newfile);

                if (ids == "")
                {
                    ids = newfile.ID.ToString();
                }
                else
                {
                    ids += "," + newfile.ID.ToString();
                }
            }

            return ids;
        }

        public static void SendSMS(string telephone, string content)
        {
            try
            {
                SmsService.LinkWS api = new SmsService.LinkWS();

                string[] tels = telephone.Trim().Replace(" ", "").Replace("\n", "").Replace("\r", "").Replace('，', ',').Split(',');

                var qz = "神州科技";
                JH_Auth_QY QYinfo = new JH_Auth_QYB().GetEntities().FirstOrDefault();
                if (QYinfo != null)
                {
                    if (!string.IsNullOrEmpty(QYinfo.DXQZ))
                    {
                        qz = QYinfo.DXQZ;
                    }
                }

                foreach (string tel in tels)
                {
                    string re = api.Send2("SY0189", "7767252812ak@@", tel, content + "【" + qz + "】", "", "");
                }

                //if (telephone.Contains(","))
                //{
                //    string re = api.BatchSend2("SY0189", "77672528", telephone, content + "【企捷】", "", ""); //群发
                //}
                //else
                //{
                //    string re = api.Send2("SY0189", "77672528", telephone, content + "【企捷】", "", "");
                //}

            }
            catch { }
        }





        private int rep = 0;

        /// <summary>
        /// 生成随机不重复的字符串（分享码用）
        /// </summary>
        /// <param name="codeCount"></param>
        /// <returns></returns>
        public string GenerateCheckCode(int codeCount)
        {
            string str = string.Empty;
            long num2 = DateTime.Now.Ticks + this.rep;
            this.rep++;
            Random random = new Random(((int)(((ulong)num2) & 0xffffffffL)) | ((int)(num2 >> this.rep)));
            for (int i = 0; i < codeCount; i++)
            {
                char ch;
                int num = random.Next();
                if ((num % 2) == 0)
                {
                    ch = (char)(0x30 + ((ushort)(num % 10)));
                }
                else
                {
                    ch = (char)(0x41 + ((ushort)(num % 0x1a)));
                }
                str = str + ch.ToString();
            }
            return str;
        }
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string GetMD5(string content)
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(content, "md5");
        }
        public static void WriteLog(string content)
        {
            if (!Directory.Exists(@"D:\FileCenter\KFYN\log"))
            {
                Directory.CreateDirectory(@"D:\FileCenter\KFYN\log");
            }
            string path = @"D:\FileCenter\KFYN\log\";
            string name = DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
            if (!File.Exists(path + name))
            {
                FileInfo myfile = new FileInfo(path + name);
                FileStream fs = myfile.Create();
                fs.Close();
            } 
            StreamWriter sw = File.AppendText(path + name);
            sw.WriteLine(content + "\r\n" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            sw.Flush();
            sw.Close();

        }
    }
}